#!/usr/bin/python
# -*- coding: utf-8 -*-
# File: utils.py
# Author: Tomás Vírseda
# License: GPL v3
# Description: utils functions for vazaar

import logging
from datetime import datetime, timedelta
import unicodedata
from rdflib import Literal, URIRef

def lastmin():
    now = datetime.now()
    date = now - timedelta(minutes=30)

    return date

def last1h():
    now = datetime.now()
    date = now - timedelta(hours=1)

    return date

def last6h():
    now = datetime.now()
    date = now - timedelta(hours=6)

    return date

def last12h():
    now = datetime.now()
    date = now - timedelta(hours=12)

    return date

def atoday():
    now = datetime.now()
    date = now - timedelta(days=1)

    return date

def aweek():
    now = datetime.now()
    date = now - timedelta(weeks=1)

    return date

def amonth():
    now = datetime.now()
    date = now - timedelta(days=31)

    return date

def asixmonths():
    now = datetime.now()
    date = now - timedelta(days=31*6)

    return date


def ayear():
    now = datetime.now()
    date = now - timedelta(days=365)

    return date

def always():
    now = datetime.now()
    date = datetime(1978, 9, 28, 23, 17, 11)

    return date

def get_predicate_object_date_filtered_query(kperiod, predicate, object):
    period = get_period(kperiod)
    speriod = Literal(period, datatype=URIRef('http://www.w3.org/2001/XMLSchema#dateTime'))
    if type(object) == Literal:
        object = """'%s'""" % object
    elif type(object) == URIRef:
        object = """xsd:anyURI(%s)""" % object

    query = """
        PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
        PREFIX nie: <http://www.semanticdesktop.org/ontologies/nie/>
        PREFIX nfo: <http://www.semanticdesktop.org/ontologies/nfo/>
        PREFIX nao: <http://www.semanticdesktop.org/ontologies/nao/>
        PREFIX pimo: <http://www.semanticdesktop.org/ontologies/pimo/>
        PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

        SELECT ?id
        WHERE
        {
            ?id rdf:type ?type .
            ?id nao:created ?date .
            ?id %s %s .
            FILTER (?type != pimo:Collection) .
            FILTER (xsd:dateTime(?date) >= xsd:dateTime('%s')) .
        }
        ORDER BY DESC(?date)
        """ % (predicate, object, speriod)
    #print query
    return query

def get_filtered_query(predicate, object):
    if type(object) == Literal:
        object = """'%s'""" % object
    elif type(object) == URIRef:
        object = """xsd:anyURI(%s)""" % object

    query = """
        PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
        PREFIX nie: <http://www.semanticdesktop.org/ontologies/nie/>
        PREFIX nfo: <http://www.semanticdesktop.org/ontologies/nfo/>
        PREFIX nao: <http://www.semanticdesktop.org/ontologies/nao/>
        PREFIX pimo: <http://www.semanticdesktop.org/ontologies/pimo/>
        PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

        SELECT ?id
        WHERE
        {
            ?id rdf:type ?type .
            ?id nao:created ?date .
            ?id %s %s .
            FILTER (?type != pimo:Collection) .
        }
        ORDER BY DESC(?date)
        """ % (predicate, object)
    #print query
    return query


def get_period(kperiod):
    period = ''

    if kperiod == 0: period = always()
    elif kperiod == 1: period = lastmin()
    elif kperiod == 2: period = last1h()
    elif kperiod == 3: period = last6h()
    elif kperiod == 4: period = last12h()
    elif kperiod == 5: period = atoday()
    elif kperiod == 6: period = aweek()
    elif kperiod == 7: period = amonth()
    elif kperiod == 8: period = asixmonths()
    elif kperiod == 9: period = ayear()
    elif kperiod == 10: period = always()
    else:
        period = atoday()

    return period

def get_date_filtered_query(kperiod):
    period = get_period(kperiod)
    # FIXME: No handlers could be found for logger "rdflib.Literal" ???
    query = """
        PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
        PREFIX nie: <http://www.semanticdesktop.org/ontologies/nie/>
        PREFIX nfo: <http://www.semanticdesktop.org/ontologies/nfo/>
        PREFIX nao: <http://www.semanticdesktop.org/ontologies/nao/>
        PREFIX pimo: <http://www.semanticdesktop.org/ontologies/pimo/>
        PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

        SELECT ?id
        WHERE
        {
            ?id rdf:type ?type .
            ?id nao:created ?date .
            FILTER (?type != pimo:Collection) .
            FILTER (xsd:dateTime(?date) >= xsd:dateTime('%s')) .
        }
        ORDER BY DESC(?date)
        """ % Literal(period, datatype=URIRef('http://www.w3.org/2001/XMLSchema#dateTime'))
    #print query
    return query
def get_date_filtered_query(kperiod):
    period = get_period(kperiod)
    # FIXME: No handlers could be found for logger "rdflib.Literal" ???
    query = """
        PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
        PREFIX nie: <http://www.semanticdesktop.org/ontologies/nie/>
        PREFIX nfo: <http://www.semanticdesktop.org/ontologies/nfo/>
        PREFIX nao: <http://www.semanticdesktop.org/ontologies/nao/>
        PREFIX pimo: <http://www.semanticdesktop.org/ontologies/pimo/>
        PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

        SELECT ?id
        WHERE
        {
            ?id rdf:type ?type .
            ?id nao:created ?date .
            FILTER (?type != pimo:Collection) .
            FILTER (xsd:dateTime(?date) >= xsd:dateTime('%s')) .
        }
        ORDER BY DESC(?date)
        """ % Literal(period, datatype=URIRef('http://www.w3.org/2001/XMLSchema#dateTime'))
    #print query
    return query


def get_search_query(search_term):
    # FIXME: No handlers could be found for logger "rdflib.Literal" ???
    query = """
        PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
        PREFIX nao: <http://www.semanticdesktop.org/ontologies/nao/>
        PREFIX nie: <http://www.semanticdesktop.org/ontologies/nie/>
        PREFIX pimo: <http://www.semanticdesktop.org/ontologies/pimo/>

        SELECT ?id
        WHERE
        {
            ?id rdf:type ?type .
            ?id nao:created ?date .
            ?id nie:title ?title .
            FILTER (?type != pimo:Collection) .
            FILTER regex(?title, "%s", "i")
        }
        ORDER BY DESC(?date)
        """ % Literal(search_term)
    #print query
    return query



def get_normal_query():
    # FIXME: No handlers could be found for logger "rdflib.Literal" ???
    query = """
        PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
        PREFIX nao: <http://www.semanticdesktop.org/ontologies/nao/>
        PREFIX pimo: <http://www.semanticdesktop.org/ontologies/pimo/>

        SELECT ?id
        WHERE
        {
            ?id rdf:type ?type .
            ?id nao:created ?date .
            FILTER (?type != pimo:Collection) .
        }
        ORDER BY DESC(?date)
        """
    #print query
    return query


def safe_name(string):
    try:
        string = string.strip()
        tmp = unicode(string, "utf-8", errors="replace")
        name = unicodedata.normalize('NFKD', tmp).encode('ascii','ignore')
        return name
    except Exception, error:
        return name

def beautiful_name(qname):
    beautiful = ""

    if qname[0:4] == 'file':
        qname = qname[4:]

    n = 1
    for letter in qname:
        if letter.isupper():
            if n > 1:
                beautiful += ' ' + letter.lower()
            else:
                beautiful += letter.lower()
        else:
            beautiful += letter
        n += 1

    return beautiful

def scale2pixbuf(width, height, filename=None):
    """
    Scale to width_max and height_max.
    Keep aspect ratio
    """
    import gtk

    pixbuf = gtk.gdk.pixbuf_new_from_file(filename)
    pixbuf=pixbuf.scale_simple(width, height, gtk.gdk.INTERP_BILINEAR)

    return pixbuf


def get_logger(name):
    log = logging.getLogger(name)
    log.setLevel(logging.DEBUG)

    #create console handler and set level to debug
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)

    #create formatter
    formatter = logging.Formatter("%(levelname)5s\t%(name)10s\t%(asctime)s | %(message)s")

    #add formatter to console handler
    ch.setFormatter(formatter)

    #add console handler to logger
    log.addHandler(ch)

    return log

def fuzzy_date(date):
    try:
        d1 = datetime.strptime(date, "%Y-%m-%d %H:%M:%S")
        d2 = datetime.now()
        rdate = d2 - d1 # DateTimeDelta
        if int(rdate.days) > 0:
            if (rdate.days >= 365):
                return "%d years ago" % int((rdate.days/365))
            else:
                return "%d days ago" % int(rdate.days)

        hours = rdate.seconds / 3600
        if int(hours) > 0:
            return "%d hours ago" % int(hours)

        minutes = rdate.seconds / 60
        if int(minutes) > 0:
            return "%d minutes ago" % int(minutes)

        if int(rdate.seconds) > 0:
            return "%d seconds ago" % int(rdate.seconds)
    except Exception, error:
        return error

